package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.CommonHandle;
import com.sjb.sixteen_journey_backend.common.ImagesProperties;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.entity.Comment;
import com.sjb.sixteen_journey_backend.entity.Follower;
import com.sjb.sixteen_journey_backend.entity.MyTime;
import com.sjb.sixteen_journey_backend.entity.OthersTicket;
import com.sjb.sixteen_journey_backend.mapper.FollowerMapper;
import com.sjb.sixteen_journey_backend.mapper.OthersTicketMapper;
import com.sjb.sixteen_journey_backend.mapper.ShowTicketMapper;
import com.sjb.sixteen_journey_backend.service.ICommentService;
import com.sjb.sixteen_journey_backend.service.IOthersTicketService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 其他晒单表 服务实现类
 * </p>
 *
 * @author jcz
 * @since 2024-07-13
 */
@Service
public class OthersTicketServiceImpl extends ServiceImpl<OthersTicketMapper, OthersTicket> implements IOthersTicketService {
    @Autowired
    private ShowTicketMapper showTicketMapper;

    @Autowired
    private CommonHandle commonHandle;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private FollowerMapper followerMapper;

    @Autowired
    private OthersTicketMapper othersTicketMapper;

    @Autowired
    private ImagesProperties imagesProperties;

    @Override
//    public R addOthersTicket(OthersTicket othersTicket, ArrayList<MultipartFile> images) {
    public R addOthersTicket(OthersTicket othersTicket) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer id = (Integer) map.get("id");
            othersTicket.setUserId(id);
            //储存图片到本地
//            List<String> files = commonHandle.saveImages(images, imagesProperties.getOthersTicket());
//            othersTicket.setPath(files.toString());
            othersTicket.setPath(othersTicket.getImages().toString());


            boolean save = this.save(othersTicket);
            if (save) {
//                Boolean b = commonHandle.addCommonness(images,id,4, othersTicket.getOthersTicketId(),"OthersTicket");
//                if(b==false) {
//                    return R.error("添加其他晒单失败");
//                }
                return R.success(null, "添加其他晒单成功");
            } else {
                return R.error("添加其他晒单失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R deleteOthersTicketById(Integer id) {
        try {
            OthersTicket myTime = this.getById(id);
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            if (userId.equals(myTime.getUserId())) {//判断是否是本人
                if (this.removeById(id)) {
                    if (commonHandle.deleteAssociationTable(myTime.getPath(), myTime.getStatus(), id, imagesProperties.getOthersTicket())) {
                        return R.success(null, "删除我的其他晒单成功");
                    }
                }
            }
            return R.error("删除我的其他晒单失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<OthersTicket>> showAllOthersTicket() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            List<OthersTicket> othersTicket = showTicketMapper.selectOthersTicket(userId);
            for (OthersTicket myTime : othersTicket) {
                commonHandle.imageByStringToList(myTime.getPath());
                List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                myTime.setImages(strings);
                //设置评论数量和当前用户对该用户是否关注
                myTime = this.setCountAndFollow(myTime);
            }
            return R.success(othersTicket, "查询成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R showAllOthersTicketById(Integer id, Boolean f) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            OthersTicket othersTicketDto = showTicketMapper.selectOthersTicketById(id,userId);
            if (othersTicketDto == null) return R.error("晒单id不正确！", 400);
            if (f) {
//                每访问一下接口，其实浏览量就增加一次
                UpdateWrapper<OthersTicket> wrapper = Wrappers.update();
                wrapper.set("pv", othersTicketDto.getPv() + 1);
                wrapper.eq("others_ticket_id", id);
                othersTicketMapper.update(null, wrapper);
                othersTicketDto = showTicketMapper.selectOthersTicketById(id,userId);
            }

            List<String> strings = commonHandle.imageByStringToList(othersTicketDto.getPath());// 设置图片列表
            othersTicketDto.setImages(strings);

            //设置评论数量和当前用户对该用户是否关注
            othersTicketDto = this.setCountAndFollow(othersTicketDto);

            return R.success(othersTicketDto, "查询成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<OthersTicket>> showAllOthersTicketByUserId() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            List<OthersTicket> othersTicket = showTicketMapper.selectOthersTicketByUserId(userId);
            for (OthersTicket myTime : othersTicket) {
                commonHandle.imageByStringToList(myTime.getPath());
                List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                myTime.setImages(strings);
                //设置评论数量和当前用户对该用户是否关注
                myTime = this.setCountAndFollow(myTime);
            }
            return R.success(othersTicket, "查询成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
@Override
    public OthersTicket setCountAndFollow(OthersTicket myTime) {
        Map<String, Object> map = ThreadLocalUtil.get();
        //我的此刻的评论数量
        QueryWrapper<Comment> query = Wrappers.query();
        query.eq("module_status",myTime.getStatus());
        query.eq("module_id", myTime.getOthersTicketId());
        long count = commentService.count(query);
        myTime.setCommentCount(count);

        Follower follower = new Follower();
        if(map!=null){
            Integer userId = (Integer) map.get("id");
            //当前用户对该用户是否关注
            QueryWrapper<Follower> followerQueryWrapper = Wrappers.query();
            followerQueryWrapper.eq("user_id",userId);
            followerQueryWrapper.eq("fans_id", myTime.getUserId());
            follower = followerMapper.selectOne(followerQueryWrapper);
        }
        myTime.setIs_followedByUser(follower==null ? false :follower.getStatus());
        return myTime;
    }
}
